#include "timer.h"

using namespace G3;

//==============================================================================
// Constructors and Destructors
//==============================================================================
G3::FPS_COUNTER::FPS_COUNTER () {
	StartCount = 0;
	EndCount = 0;
	LastDelta = 0;
	FrameCount = 0;
	LastFPS = 0.0;
	FPS = 0.0;
}

G3::TIMER::TIMER () {
	StartCount = 0;
}

//==============================================================================
// Starts or restarts the FPS counter
//==============================================================================
void G3::FPS_COUNTER::Start () {
	FrameCount = 0;
	FPS = 0.0;
	LastFPS = 0.0;

	StartCount = SDL_GetTicks ();
	EndCount = StartCount;
}

//==============================================================================
// Marks another frame as rendered
//
//	Returns the number of frames already rendered within this second
//==============================================================================
long G3::FPS_COUNTER::AddFrame () {
	FrameCount++;

	return FrameCount;
}

//==============================================================================
// Checks time and updates the FPS variable
//==============================================================================
void G3::FPS_COUNTER::CheckTime () {
	long t = (long) SDL_GetTicks ();

	if (t - StartCount >= 1000 || t < StartCount) {
		LastFPS = FPS;
		LastDelta = t - StartCount;
		FPS = 1000.0 * ((double) FrameCount) / ((double) LastDelta);

		FrameCount = 0;
		EndCount = t;
		StartCount = EndCount;
	}
}

//==============================================================================
// Starts or restarts the timer
//==============================================================================
void G3::TIMER::Start () {
	StartCount = SDL_GetTicks ();
}

//==============================================================================
// Checks time and returns the number of ticks since the last check
//==============================================================================
long G3::TIMER::CheckTime () {
	long t = (long) SDL_GetTicks ();
	long t2 = t - StartCount;

	StartCount = t;

	return t2;
}

//==============================================================================
// Returns the elapsed time since the last check
//==============================================================================
long G3::TIMER::GetElapsedTime () {
	long t = (long) SDL_GetTicks ();

	return (t - StartCount);
}
